<template>
  <view class="container">
    <!-- 主操作按钮 -->
    <view class="action-buttons">
      <button class="btn bluetooth-btn" @click="toggleBluetooth">
        {{ bluetooth === 1 ? '打开蓝牙' : '关闭蓝牙' }}
      </button>
      <button class="btn search-btn" @click="openBluetoothAdapter">搜索设备</button>
    </view>

    <!-- 已配对设备区域 -->
    <view class="paired-section">
      <view class="section-title">已配对设备</view>
      <scroll-view class="paired-list" scroll-y>
        <view v-for="(item,index) in pairedList" :key="index" class="paired-item" @click="setSelectedPaired(item)">
          <view class="device-info">
            <text>{{item.name || item.address}}</text>
            <text class="selected-tag" v-if="item.isSelected==1">&nbsp;&nbsp;已选中</text>
          </view>
          <view class="delete-btn" @click.stop="removePaire(index)">删除设备</view>
        </view>
      </scroll-view>
    </view>

    <!-- 未配对设备区域 -->
    <view class="unpaired-section">
      <view class="section-title">
        <view class="tip-text">说明：如果反复操作连不到蓝牙，请退出重新登录。</view>
        <view>未配对设备</view>
      </view>
      <scroll-view class="unpaired-list" scroll-y>
        <view v-for="(item,index) in unpairedList" :key="index" class="unpaired-item"
          @click="createBLEConnection(item.address)">
          {{item.name || item.address}}
        </view>
      </scroll-view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-buttons">
      <button class="btn close-btn" @click="close">关闭页面</button>
    </view>
  </view>
</template>

<script>
import { 
  getUuid, 
  setUuid, 
  DEFAULT_UUID,
  getBluetoothConnection,
  setBluetoothConnection,
  removeBluetoothConnection
} from '@/utils/bluetooth.js'
  
export default {
  name: 'TtBluetooth',
  data() {
    return {
      bluetooth: 1, //1：打开蓝牙  2：关闭蓝牙
      title: '蓝牙管理',
      searchLoadingTxt: '',
      isBlueOk: false,
      bluetimestoper: null,
      startchecktimer: null,
      timeoutOfBlueScanFailure30s: 300000,
      baseList: [],
      bluetoothIndex: [],
      targetDeviceName: '',
      _deviceId: '', //蓝牙deviceId
      pairedList: [], //已配对蓝牙
      pairedLists: [], //已配对蓝牙集合
      pairedHeight: 0, //已配对蓝牙显示高度
      unpairedList: [], //未配对蓝牙
      unpairedHeight: 0, //未配对蓝牙显示高度
      bluetoothSocket: null, //蓝牙socket连接
      sendData: '', //要发送的数据(不再使用)
      currentDevice: null, //当前连接的设备
      receiveData: '', // 存储接收到的数据
      inputStream: null, // 输入流对象
      isReceiving: false, // 是否正在接收数据
      uuid: DEFAULT_UUID // 当前使用的UUID
    }
  },
  onLoad() {
    // 检查并设置UUID
    this.checkAndSetUuid();
    //判断蓝牙打开状态
    this.bluetoothStatus();
    // 从缓存加载蓝牙连接信息
    const connection = getBluetoothConnection();
    if (connection) {
      this.currentDevice = connection.device;
    }
  },
  beforeDestroy() {
    // 组件销毁时释放资源
    this.stopReceiving();
  },
  methods: {
    // 检查并设置UUID
    checkAndSetUuid() {
      const savedUuid = getUuid();
      if (!savedUuid) {
        this.promptForUuid();
      } else {
        this.uuid = savedUuid;
      }
    },
    
    // 提示用户输入UUID
    promptForUuid() {
      uni.showModal({
        title: '蓝牙UUID设置',
        content: '请输入蓝牙设备的UUID',
        editable: true,
        placeholderText: DEFAULT_UUID,
        confirmText: '确定',
        cancelText: '使用默认值',
        success: (res) => {
          let finalUuid = DEFAULT_UUID;
          if (res.confirm && res.content.trim()) {
            finalUuid = res.content.trim();
          }
          setUuid(finalUuid);
          this.uuid = finalUuid;
          uni.showToast({
            title: `UUID已设置为: ${finalUuid}`,
            icon: 'none'
          });
        }
      });
    },
    
    // 停止接收并释放蓝牙资源
    // stopReceiving() {
    //   try {
    //     if (this.inputStream) {
    //       this.inputStream.close();
    //       this.inputStream = null;
    //     }
    //     if (this.bluetoothSocket) {
    //       this.bluetoothSocket.close();
    //       this.bluetoothSocket = null;
    //     }
    //     console.log("蓝牙资源已释放");
    //   } catch (e) {
    //     console.error("停止接收数据失败:", e);
    //   }
    // },
    
    //关闭页面(修改后的方法，不再释放资源)
    close() {
      // 只触发关闭事件，不释放资源
      this.$emit('close-bluetooth');
      // 注意：这里不再调用 this.stopReceiving()
    },

    // 删除已配对设备
    removePaire(index) {
      var that = this;
      uni.showModal({
        title: "提示",
        content: "是否删除设备",
        showCancel: true,
        cancelText: "取消",
        confirmText: "确定",
        success(res) {
          if (res.confirm) {
            var address = uni.getStorageSync("printerSelected").address;
            if (that.pairedList[index].address == address) {
              uni.setStorageSync("printerSelected", "");
              that.currentDevice = null;
            }
            for (var i = 0; i < that.pairedLists.length; i++) {
              if (that.pairedLists[i].getAddress() == that.pairedList[index].address) {
                that.pairedLists[i].removeBond();
              }
            }
            that.pairedList.splice(index, 1);
          }
        }
      })
    },

    //设置已选中蓝牙
    setSelectedPaired(paired) {
      var that = this;
      for (var i = 0; i < that.pairedList.length; i++) {
        if (that.pairedList[i].address == paired.address) {
          that.pairedList[i].isSelected = 1;
          that.connectToDevice(paired.address);
        } else {
          that.pairedList[i].isSelected = 0;
        }
      }
      uni.showToast({
        title: "已选中",
        icon: "success"
      })
      paired.isSelected = 1;
      uni.setStorageSync("printerSelected", paired);
    },

    //判断蓝牙打开状态
    bluetoothStatus() {
      var that = this;
      const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
      const blueadapter = BluetoothAdapter.getDefaultAdapter();
      
      if (blueadapter) {
        if (blueadapter.isEnabled()) {
          that.bluetooth = 0;
          var yilianjie = uni.getStorageSync("printerSelected");
          var selectAddress = "";
          if (yilianjie) {
            selectAddress = yilianjie.address;
            that.connectToDevice(selectAddress);
          }

          //获取手机已配对蓝牙
          var lists = blueadapter.getBondedDevices();
          plus.android.importClass(lists);
          var iterator = lists.iterator();
          plus.android.importClass(iterator);
          while (iterator.hasNext()) {
            var device = iterator.next();
            that.pairedLists.push(device);

            plus.android.importClass(device);
            that.pairedList.push({
              name: device.getName(),
              address: device.getAddress(),
              isSelected: selectAddress == device.getAddress() ? '1' : '0'
            })
          }
        } else {
          this.bluetooth = 1;
          this.pairedList = [];
          this.currentDevice = null;
        }
        this.unpairedList = [];
      }
    },

    //打开/关闭蓝牙
    toggleBluetooth() {
      if (this.bluetooth == 1) {
        this.openBluetooth();
      } else {
        this.closeBluetooth();
      }
    },

    //打开蓝牙
    openBluetooth() {
      var that = this;
      uni.showModal({
        title: "提示",
        content: "蓝牙尚未打开，是否打开蓝牙",
        showCancel: true,
        cancelText: "取消",
        confirmText: "确定",
        success(res) {
          if (res.confirm) {
            const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
            const blueadapter = BluetoothAdapter.getDefaultAdapter();
            if (blueadapter != null) {
              that.bluetooth = 0;
              blueadapter.enable();

              setTimeout(function() {
                that.bluetoothStatus();
              }, 2000)
            }
          }
        }
      })
    },

    //关闭蓝牙
    closeBluetooth() {
      var that = this;
      uni.showModal({
        title: "提示",
        content: "蓝牙已打开，是否关闭蓝牙",
        showCancel: true,
        cancelText: "取消",
        confirmText: "确定",
        success(res) {
          if (res.confirm) {
            const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
            const blueadapter = BluetoothAdapter.getDefaultAdapter();
            if (blueadapter != null) {
              that.bluetooth = 1;
              that.pairedList = [];
              that.unpairedList = [];
              that.currentDevice = null;
              that.receiveData = '';
              uni.setStorageSync("printerSelected", "");
              if (that.bluetoothSocket) {
                try {
                  that.bluetoothSocket.close();
                } catch (e) {
                  console.log("关闭socket错误:", e);
                }
                that.bluetoothSocket = null;
              }
              if (that.inputStream) {
                try {
                  that.inputStream.close();
                } catch (e) {
                  console.log("关闭输入流出错:", e);
                }
                that.inputStream = null;
              }
              blueadapter.disable();
            }
          }
        }
      })
    },

    //初始化蓝牙模块
    openBluetoothAdapter() {
      if (this.bluetooth == 1) {
        uni.showToast({
          title: "请先打开蓝牙",
          icon: "error"
        })
        return;
      }
      
      let system = uni.getSystemInfoSync();
      if (system.platform === 'android') {
        var that = this;
        var context = plus.android.importClass("android.content.Context");
        var locationManager = plus.android.importClass("android.location.LocationManager");
        var main = plus.android.runtimeMainActivity();
        var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        
        if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
          uni.showModal({
            title: "提示",
            content: "请打开定位服务功能",
            showCancel: false,
            success() {
              if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
                var Intent = plus.android.importClass('android.content.Intent');
                var Settings = plus.android.importClass('android.provider.Settings');
                var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                main.startActivity(intent);
              }
            }
          });
          return false
        } else {
          that.searchDevices()
          return true
        }
      }
    },

    //搜索蓝牙
    searchDevices() {
      var that = this;
      that.unpairedList = [];

      uni.openBluetoothAdapter({
        success(res) {
          uni.getBluetoothAdapterState({
            success: function(res) {
              if (res.available) {
                uni.startBluetoothDevicesDiscovery({
                  success(res) {
                    var main = plus.android.runtimeMainActivity();
                    var IntentFilter = plus.android.importClass('android.content.IntentFilter');
                    var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
                    var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
                    var BAdapter = BluetoothAdapter.getDefaultAdapter();

                    uni.showLoading({
                      title: "开始搜索设备",
                    })

                    var filter = new IntentFilter();
                    var bdevice = new BluetoothDevice();
                    BAdapter.startDiscovery();
                    var receiver;
                    receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
                      onReceive: function(context, intent) {
                        plus.android.importClass(intent);
                        if (intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
                          main.unregisterReceiver(receiver);
                          console.log("搜索结束");
                          uni.hideLoading();
                        } else {
                          if (intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getBondState() === 10) {
                            var y = 0;
                            for (let x = 0; x < that.unpairedList.length; x++) {
                              if (that.unpairedList[x].address == intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress()) {
                                y++;
                              }
                            }
                            if (y > 0) {
                              y = 0;
                            } else {
                              that.unpairedList.push({
                                name: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getName(),
                                address: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress()
                              })
                            }
                          }
                        }
                      }
                    });
                    filter.addAction(bdevice.ACTION_FOUND);
                    filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
                    filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
                    filter.addAction(BAdapter.ACTION_STATE_CHANGED);
                    main.registerReceiver(receiver, filter);
                  }
                })
              }
            },
          })
        }
      })
    },

    //连接打印机
    createBLEConnection(mac_address) {
      if (!mac_address) {
        uni.showToast({
          title: "请选择蓝牙打印机",
          icon: "none"
        });
        return;
      }

      var main = plus.android.runtimeMainActivity();
      var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
      var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
      var UUID = plus.android.importClass("java.util.UUID");
      var BAdapter = BluetoothAdapter.getDefaultAdapter();
      var device = BAdapter.getRemoteDevice(mac_address);
      plus.android.importClass(device);
      var bdevice = new BluetoothDevice();
      var that = this;

      if (device.getBondState() == bdevice.BOND_NONE) {
        console.log("未配对蓝牙设备：" + device.getName() + '    ' + device.getAddress());
        if (mac_address == device.getAddress()) {
          if (device.createBond()) {
            console.log("配对成功")
            var cha = setInterval(function() {
              if (device.getBondState() == bdevice.BOND_BONDED) {
                clearInterval(cha);
                for (var i = 0; i < that.unpairedList.length; i++) {
                  if (that.unpairedList[i].address == mac_address) {
                    that.pairedList.push({
                      name: that.unpairedList[i].name,
                      address: that.unpairedList[i].address,
                      isSelected: '0'
                    });
                    that.unpairedList.splice(i, 1);
                    break;
                  }
                }
                that.connectToDevice(mac_address);
              }
            }, 1000)
          }
        }
      } else {
        that.connectToDevice(mac_address);
      }
    },

    // 连接到设备
    connectToDevice(mac_address) {
      var that = this;
      uni.showLoading({
        title: '正在连接...'
      });

      try {
        if (that.bluetoothSocket) {
          that.bluetoothSocket.close();
          that.bluetoothSocket = null;
        }
        if (that.inputStream) {
          that.inputStream.close();
          that.inputStream = null;
        }

        const BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
        const BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
        const UUID = plus.android.importClass("java.util.UUID");
        const BAdapter = BluetoothAdapter.getDefaultAdapter();
        const device = BAdapter.getRemoteDevice(mac_address);
        plus.android.importClass(device);

        // 使用缓存的UUID
        const uuid = UUID.fromString(this.uuid);

        const socket = device.createRfcommSocketToServiceRecord(uuid);
        plus.android.importClass(socket);

        new Promise((resolve, reject) => {
          try {
            socket.connect();
            resolve(socket);
          } catch (e) {
            reject(e);
          }
        }).then(socket => {
          that.bluetoothSocket = socket;
          that.currentDevice = device;
          
          // 缓存蓝牙连接信息
          setBluetoothConnection(socket, device);

          uni.hideLoading();
          uni.showToast({
            title: '连接成功',
            icon: 'success'
          });

          for (var i = 0; i < that.pairedList.length; i++) {
            if (that.pairedList[i].address == mac_address) {
              that.pairedList[i].isSelected = 1;
              uni.setStorageSync("printerSelected", that.pairedList[i]);
            } else {
              that.pairedList[i].isSelected = 0;
            }
          }
          
          // 通知父组件连接状态已更新
          that.$emit('device-connected', {
            device: device,
            address: mac_address
          });
        }).catch(e => {
          uni.hideLoading();
          uni.showToast({
            title: '连接失败: ' + e.message,
            icon: 'none'
          });
          console.error("连接失败:", e);
        });
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: '连接异常: ' + e.message,
          icon: 'none'
        });
        console.error("连接异常:", e);
      }
    },
    
    // 发送数据到设备(现在由父组件处理)
    sendDataToDevice() {
      // 这个方法在组件中不再需要，因为发送区域已移出组件
    },
    
    // 新增方法：获取当前选中的设备地址
    getSelectedDeviceAddress() {
      for (let item of this.pairedList) {
        if (item.isSelected == 1) {
          return item.address;
        }
      }
      return null;
    },
    
    // 新增公开方法：供父组件调用发送数据
    publicSendData(data) {
      if (!data || data.trim() === '') {
        uni.showToast({
          title: '请输入要发送的数据',
          icon: 'none'
        });
        return;
      }
      
      // 调用原有的发送逻辑
      this.sendDataToDeviceWithData(data);
    },
    
    // 将原来的发送方法重构为内部方法
    sendDataToDeviceWithData(data) {
      // 优先使用当前连接的socket，如果没有则尝试从缓存获取
      let socket = this.bluetoothSocket;
      let device = this.currentDevice;
      
      if (!socket || !device) {
        const connection = getBluetoothConnection();
        if (connection) {
          device = connection.device;
          // 需要重新建立连接
          this.connectToDevice(device.address);
          return;
        }
      }
      
      if (!socket || !device) {
        uni.showToast({
          title: '请先连接蓝牙设备',
          icon: 'none'
        });
        return;
      }
    
      if (!data || data.trim() === '') {
        uni.showToast({
          title: '请输入要发送的数据',
          icon: 'none'
        });
        return;
      }
    
      try {
        const OutputStream = plus.android.importClass("java.io.OutputStream");
        const os = socket.getOutputStream();
        plus.android.importClass(os);
    
        // 将字符串转换为字节数组
        const bytes = data.split('').map(c => c.charCodeAt(0));
        os.write(bytes);
        os.flush();
    
        uni.showToast({
          title: '发送成功',
          icon: 'success'
        });
      } catch (e) {
        uni.showToast({
          title: '发送失败: ' + e.message,
          icon: 'none'
        });
        console.error("发送失败:", e);
        
        // 发送失败可能是连接已断开，清除缓存
        removeBluetoothConnection();
        this.bluetoothSocket = null;
        this.currentDevice = null;
      }
    }
  }
}
</script>

<style>
@import '@/static/css/index.css'
</style>